package demo

import (
	"errors"
	"fmt"

	s "gitee.com/xiaoa7/jsetl/service"
	jsvmcore "gitee.com/xiaoa7/jsvm-core"
	"github.com/dop251/goja"
)

// 获取数据库实例
func getInstance(id string) (*DemoService, error) {
	if ins := s.GetService(id); ins != nil {
		if _redis, ok := ins.(*DemoService); ok {
			return _redis, nil
		} else {
			return nil, errors.New("demo instance type error")
		}
	}
	return nil, errors.New("can't find demo instance")
}

// 样例方法
func (d *DemoService) SayHello(name string) string {
	return fmt.Sprintf("Hello,%s!", name)
}

// 初始化
func init() {
	jsvmcore.RegisterObject("demo", map[string]jsvmcore.HandleFn{
		//打开excel文件
		"sayhello": func(vm *jsvmcore.JsVM) jsvmcore.JsVmFn {
			return func(params ...interface{}) goja.Value {
				if len(params) < 2 {
					return vm.State.ToValue("无效的输入参数")
				}
				demoInstance, _ := params[0].(string)
				name, _ := params[1].(string)
				if ins, err := getInstance(demoInstance); err == nil {
					ret := ins.SayHello(name)
					return vm.State.ToValue(ret)
				} else {
					return vm.State.ToValue(err.Error())
				}
			}
		},
	})
}
